package com.david.apipassenger.gray;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;

import java.util.List;
import java.util.Map;

public class GrayRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        return null;
    }

    public Server choose(ILoadBalancer lb,Object key){

        System.out.println("灰度  rule");
        Server server=null;
        while(server==null){
            //获取所有可以达到的服务
            List<Server> reachableServers = lb.getReachableServers();


            //获取当前线程的参数 用户id version=1
            Map<String,String> map = RibbonParameters.get();

            String version="";
            if (map!=null&& map.containsKey("version")){
                version=map.get("version");
            }
            System.out.println("当前rule versoin："+version);


            //根据用户选择服务
            for (int i = 0; i < reachableServers.size(); i++) {
                server=reachableServers.get(i);
                //用户的version有了，服务的自定义meta还是没有，灰度的规则是从自定义的meta中获取的

                /**
                 * meta信息如下
                 * eureka:
                 *   instance:
                 *     metadata-map:
                 *       version: v2
                 */
                //Server.MetaInfo metaInfo = server.getMetaInfo();  这个方法获取不到meta的信息

                Map<String, String> metadata = ((DiscoveryEnabledServer) server).getInstanceInfo().getMetadata();
                String version1 = metadata.get("version");
                //两者匹配则break
                if (version.trim().equals(version1)){
                    break;
                }
            }

        }
        return server;
    }
}
